package com.example.project.projectspringcloud.controller;

import com.example.project.projectspringcloud.entity.user.User;
import com.example.project.projectspringcloud.utils.DeviceUtil;
import com.example.project.projectspringcloud.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 公共Controller
 */
public class BaseController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private MessageSource messageSource;

    public static User getCurrentUser() {
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal.equals("anonymousUser")) {
                return null;
            }
            return (User) principal;
        }
        return null;
    }

    public static Integer getCurrentUserId() {
        if (getCurrentUser() != null) {
            return getCurrentUser().getId();
        } else {
            return null;
        }
    }

    /**
     * 获取error国际化资源
     *
     * @param bindingResult
     * @return
     */
    public String translateI18N(BindingResult bindingResult) {
        return StringUtil.translateI18N(this.messageSource, bindingResult);
    }

    /**
     * 获取对应国际化资源
     *
     * @param source
     * @return
     */
    public String translateI18N(String source) {
        return StringUtil.translateI18N(this.messageSource, source);
    }

    /**
     * 是否是移动设备
     *
     * @return
     */
    public boolean isMobile() {
        return DeviceUtil.isMobile(request.getHeader("USER-AGENT"));
    }
}
